﻿using System;
using System.IO;
using System.Text;
using System.Threading;

namespace TopVisionLog
{
    public class TVLog
    {
        public static string Folder = AppDomain.CurrentDomain.BaseDirectory + "TVlog";

        public static string Title = "";

        public static string FileFormat = "log";

        private static string logFile = "";

        public static void WriteLine(string message)
        {
            try
            {
                if (!IsFolderExist(Folder))
                {
                    CreatFolder(Folder);
                    Console.WriteLine(Folder);
                }

                if (logFile == "" || !File.Exists(logFile))
                    CreatFile();

                var logStream = File.OpenWrite(logFile);

                logStream.Position = logStream.Length;

                byte[] byData = Encoding.UTF8.GetBytes("\r\n[" + DateTime.Now.ToString("F", Thread.CurrentThread.CurrentCulture) + "] " + message);

                logStream.Write(byData, 0, byData.Length);

                logStream.Close();

                logStream.Dispose();
            }
            catch
            {

            }
        }

        private static bool IsFolderExist(string folder)
        {
            return Directory.Exists(folder);
        }

        private static void CreatFolder(string path)
        {
            try
            {
                if (!IsFolderExist(path))
                {
                    Directory.CreateDirectory(path);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private static string CreatFile()
        {
            try
            {
                var files = Directory.GetFiles(Folder);

                string Y = DateTime.Now.Year.ToString();
                string M = DateTime.Now.Month.ToString();
                string D = DateTime.Now.Day.ToString();
                string I = (files.Length + 1).ToString();

                string name = (Title == "" ? "" : Title + "_") + Y + "_" + M + "_" + D + "_" + I + (FileFormat == "" ? "" : "." + FileFormat);
                string path = Path.Combine(Folder, name);

                logFile = path;

                File.WriteAllText(path, "");

                return logFile;
            }
            catch (Exception ex)
            {
                logFile = "";
                throw ex;
            }
        }
    }
}
